//
//  KDVpnDataTool.m
//  PublicSentimentMonitorSystem
//
//  Created by 魏强 on 15/12/10.
//  Copyright © 2015年 魏强. All rights reserved.
//

#import "KDVpnDataTool.h"
#import "KDVpnModel.h"
#import "FMDB.h"
static NSString *const vpnStoreKey = @"vpnStoreKey";
@implementation KDVpnDataTool
static FMDatabase *_db;

+ (void)initialize
{
    //1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"KDVpnModel.sqlite"];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    //2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_vpnModel (id integer PRIMARY KEY AUTOINCREMENT, vpnModel blob NOT NULL,date text NOT NULL);"];
}
//根据请求参数读取相应的数据
+ (NSArray *)Vpnlist
{
    //根据请求参数生成对应的查询SQL语句
    NSString *sql = [NSString stringWithFormat:@"SELECT *FROM t_vpnModel WHERE date = '%@'", vpnStoreKey];
    FMResultSet *set = [_db executeQuery:sql];
    NSMutableArray *baseBoards = [NSMutableArray array];
    while (set.next) {
        //NSData ————》NSDictionary
        NSData *data = [set objectForColumnName:@"vpnModel"];
        KDVpnModel *vipmodel = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [baseBoards addObject:vipmodel];
    }
    if (baseBoards.count == 0) {//
        return nil;
    }
    return baseBoards;
}
/**
 *  保存今天刷新的vpn列表数据
 */
+ (void)saveVpnList:(NSArray *)vipList
{
    if (!vipList.count) {
        return;
    }
    //清空数据库
    [_db executeUpdate:@"DELETE FROM t_vpnModel"];
    for (KDVpnModel *model in vipList) {
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:model];
        [_db executeUpdateWithFormat:@"replace into t_vpnModel (vpnModel, date) VALUES (%@, %@);", data,vpnStoreKey];
    }
}
@end
